const app = getApp();
Page({
    data: {
        isAll:'',
        user:{},
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        CartList: [],
        cids:[],
        checkCartList: [],
        checkNum: '',
        checkPrice: ''
    },
    onLoad: function (options) {
      this.CartList()
      this.checkboxChange()
    },
    submit: function () {
        wx.navigateTo({
            url: '/pages/scar/order/index'
        })
    },
    CartList:function(){
      let _this = this
      wx.getStorage({
        key: 'user',
        success: (res)=>{
          wx.request({
            method:'GET',
            url: 'http://localhost:8989/cart/uid/' + res.data.uid,
            success:(res) => {
              _this.setData({
                CartList: res.data.data
              })
              console.log(_this.data.CartList)
            }
          })
        }
      })
    },
    checkboxChange:function(e){
      let _this = this
      let list = new Array()
      console.log("check方法触发")
      console.log(e)
      for(let i = 0; i < e.detail.value.length; i ++){
        list.push(Number(e.detail.value[i]))
      }
      _this.setData({
        cids: list
      })
      _this.AllSum()
      console.log(_this.data.cids)
    },
    goOrder:function(e){
      let _this = this
      let cids = _this.data.cids
      wx.navigateTo({
        url: `/pages/scar/order/index?cids=${JSON.stringify(cids)}&orderid=${JSON.stringify()}`,
      })
    },
    AllSum:function(){
      let _this = this
      let checkNum = 0
      let checkPrice = 0
      wx.request({
        method:"GET",
        url: 'http://localhost:8989/cart/ids/' + _this.data.cids,
        success:(res) => {
          console.log(res)
          if(res.data.code === '302'){
            console.log("用户还没有选择购物车商品")
          }
          for(let i = 0; i < res.data.data.length; i ++){
            checkNum += res.data.data[i].num
            checkPrice += (res.data.data[i].num * res.data.data[i].price)
          }
          _this.setData({
            checkNum: checkNum,
            checkPrice: checkPrice
          })
        }
      })
    },
    updateCart:function(e){
      console.log(e)
      let _this = this
      wx.request({
        method:'POST',
        url: 'http://localhost:8989/cart',
        data:{
            cid: e.currentTarget.dataset.cid,
            num: e.currentTarget.dataset.num,
        },
        success:(res)=>{
          console.log(res)
          _this.onLoad()
        }
      })
    },
    deleteCids:function(){
      let _this = this
      wx.request({
        method:'POST',
        url: 'http://localhost:8989/cart/del/batch/' + _this.data.cids,
        success:(res)=>{
          console.log("删除成功")
          _this.onLoad()
        }
      })
    }
});
